package com.tian.arch.base

import android.app.Dialog
import androidx.lifecycle.*

/**
 * 绑定LifecycleOwner，在销毁时自动销毁添加的对象，如Dialog、Disposable、Destroyable
 */
interface IDisposableManager {
    fun init(lifecycleOwner: LifecycleOwner)
    fun handleDialog(dialog: Dialog)
    fun addDestroyable(destroyable: Destroyable)
}

class DisposeManager : IDisposableManager, LifecycleObserver {

    private val mDialogs: MutableList<Dialog> = ArrayList()
    private val mDestroyable: MutableList<Destroyable> = ArrayList()

    override fun init(lifecycleOwner: LifecycleOwner) {
        lifecycleOwner.lifecycle.addObserver(this)
    }

    override fun handleDialog(dialog: Dialog) {
        mDialogs.add(dialog)
    }

    override fun addDestroyable(destroyable: Destroyable) {
        mDestroyable.add(destroyable)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        mDialogs.forEach { if (it.isShowing) it.dismiss() }
        mDialogs.clear()
        mDestroyable.forEach { it.onDestroy() }
        mDestroyable.clear()
    }
}




